#coding=utf-8
import os,random,urllib,datetime
BASEURL = 'http://jpg-server.appspot.com'
MAX = 10000

def get_file_name():
  while True:
    name = '%s.jpg'%str(random.randrange(0,MAX))
    query = Image.all()
    query.filter('name =', name)
    if query.count() == 0:
      return name
      
import wsgiref.handlers

from google.appengine.ext import db, blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import images
from google.appengine.ext.webapp import blobstore_handlers

class MainHandler(webapp.RequestHandler):
  def get(self):
    upload_url = blobstore.create_upload_url('/upload')
    self.response.out.write('<html><body>')
    self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
    self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" 
        name="submit" value="Submit"> </form></body></html>""")

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
    blob_info = upload_files[0]
    self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

class Image(db.Model):
  name = db.StringProperty(required=True)
  content = db.BlobProperty()
  created_at = db.DateTimeProperty(auto_now_add=True)
  note = db.StringProperty(multiline=True)
  #n: 获取图像的次数 
  n = db.IntegerProperty(default=0)
  
class JPGHandler(webapp.RequestHandler):
  def post(self):
    name = get_file_name()
    
    note = self.request.get('note')
    content = self.request.get('image')
    
    img = images.Image(content)
    #img.im_feeling_lucky()
    content = img.execute_transforms(output_encoding=images.JPEG)
    Image(name=name, content=content, note=note).put()
    
    url = BASEURL + '/jpg?name=%s'%name
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write('<a href=%s>%s</a>'%(url, name))

  def get(self):
    name = self.request.get("name")
    query = Image.all()
    query.filter('name =', name)
    p = query.get()
    p.n = p.n + 1
    p.put()
    
    self.response.headers['Content-Type'] = 'image/jpeg'
    self.response.out.write(p.content)

class Index(webapp.RequestHandler):
  def get(self):
    self.redirect('/html/upload.html')
    
class PostTest(webapp.RequestHandler):
  def get(self):
    self.response.out.write('''
        <html>
          <body>
            <form action="/p2" method="POST">
              <p>Name: <input type="text" name="name" /></p>
              <p>Favorite foods:</p>
              <select multiple size="4">
                <option value="apples">Apples</option>
                <option value="bananas">Bananas</option>
                <option value="carrots">Carrots</option>
                <option value="durians">Durians</option>
              </select>
              <p>Birth year: <input type="text" name="birth_year" /></p>
              <input type="submit" name="submit" value="Submit"> <br/>
              <a href='/'>首页</a>

            </form>
          </body>
        </html>
        ''')

        
  def post(self):
    name = self.request.get("name")
    favorite_foods = self.request.get_all("favorite_foods")
    birth_year = self.request.get_range("birth_year",
                                        min_value=1900,
                                        max_value=datetime.datetime.utcnow().year)
                                        #default_value=1900)
    data = dict(self.request.POST)
    self.response.out.write(data)
    self.response.out.write(name)
    self.response.out.write(favorite_foods)
    self.response.out.write(birth_year)

from google.appengine.ext import db
class EntryPoint(db.Model):
  url = db.TextProperty(required=True)
  
class TestD(webapp.RequestHandler):
  def get(self):
    EntryPoint(key_name='1', url='1').put()
    
application = webapp.WSGIApplication([
  ('/jpg', JPGHandler),
  ('/', Index),
  
  ('/p2', PostTest),
  
  ('/b', MainHandler),
  ('/upload', UploadHandler),
  ('/serve/([^/]+)?', ServeHandler),
  
  ('/td', TestD),
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
